//
//  BTScoolOfMangementVC.m
//  BaxTer
//
//  Created by 陈武琦 on 16/8/30.
//  Copyright © 2016年 陈武琦. All rights reserved.
//

#import "BTScoolOfMangementVC.h"
#import "BTSchoolHorCell.h"
#import "SchoolManagerSectionHeader.h"
#import "XLPlainFlowLayout.h"
#import "KCBannerView.h"
#import "BTSchoolVerCell.h"
#import "BTSchoolCourseList.h"
#import "BTBannerModel.h"
#import "BTManagerItemModel.h"
#import "CWQ_historySearchVC.h"
#import "BTCourseDetailVC.h"
#import "BTTopicDetailVC.h"
#import "UICollectionView+ResponseToEventOutOfSuperView.h"
#import "BTSearchBar.h"
#import "CWQ_MessageVC.h"
#import "UIView+WZLBadge.h"
#import "BTBaseWebVC.h"
#define banerHight 180
@interface BTScoolOfMangementVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,KCBannerViewDataSource,KCBannerViewDelegate,UISearchBarDelegate>
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;


@property (nonatomic,  strong) KCBannerView *banner;
@property (nonatomic,  strong) NSArray<BTBannerModel *> *bannerArr;

@property (nonatomic,  strong) UIButton *notiBtn;

@property (nonatomic,  strong) BTSearchBar *searchBar;


@end

@implementation BTScoolOfMangementVC

- (void)viewDidLoad {
    [super viewDidLoad];
      [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshDataSource) name:LoginSuccessNotification object:nil];
   
}

#pragma mark -请求数据
- (void)refreshDataSource {
    
    //重新初始化数据库/切换
    [[RLMCourseManager manager] configWithUserAccout:BT_USERID];
    [self getBanerData];
    [self getManagerSchoolList];
   
}

#pragma mark -轮播视图
- (KCBannerView *)banner{
    if (!_banner) {
        // 创建
        _banner  = [[KCBannerView alloc] init];
       
        _banner.placeholderImageView.image = [UIImage imageNamed:@"暂无图片"];
        // 设置代理
        _banner.delegate = self;
        // 数据源
        _banner.dataSource = self;
        // 添加
        
        
    }
    return _banner;
}
#pragma mark -KCBannerViewDatasource
- (BTBannerModel *)bannerView:(KCBannerView *)bannerView bannerForItemAtIndex:(NSInteger)index
{
    return self.bannerArr[index];
}

- (NSInteger)numberOfBannersInBannerView:(KCBannerView *)bannerView
{
    return self.bannerArr.count;
}

- (void)bannerView:(KCBannerView *)bannerView didSelectBannerAtIndex:(NSInteger)index{
    BTBannerModel *bannerModel = self.bannerArr[index];
    [self gotoToRelativeCourseWith:[bannerModel.generalizeType integerValue] with:[bannerModel.generalizeContent integerValue] with:bannerModel.name ifIsConsultWithType:bannerModel.infoType andQuestionId:[bannerModel.infoQuestionID integerValue]];
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    [self toSearch];
    return NO;
}


- (void)gotoToRelativeCourseWith:(NSInteger)generalizeContent with:(NSInteger)modelId with:(NSString *)name ifIsConsultWithType:(NSString *)infoType andQuestionId:(NSInteger)infoQuestionID{
    NSInteger type = generalizeContent;
    NSInteger itemId = modelId;
    if (type ==1) {
        BTCourseDetailVC *vc =[BTCourseDetailVC new];
        vc.courseId = itemId;
        [self.navigationController pushViewController:vc animated:YES];
        [self.navigationController setNavigationBarHidden:YES animated:YES];
        return;
    }
    if (type ==2) {
        BTTopicDetailVC *vc =[BTTopicDetailVC new];
        vc.topicId = itemId;
        vc.title = name;
        [self.navigationController pushViewController:vc animated:YES];
        
        return;
    }
    if (type==3) {
        
        
        BTBaseWebVC *vc =[BTBaseWebVC new];
        NSString *typeStr = nil;
        NSString *url;
        if ([infoType isEqualToString:@"ORDINARY"]) {
            typeStr = kConsultDetail;
            url = [NSString stringWithFormat:@"%@/%@/%@",[BTNetworkManager sharedMg].bathURL,typeStr,@(modelId)];
        }else if([infoType isEqualToString:@"QUESTION"]){
            typeStr = kQuestionDetai;
            url = [NSString stringWithFormat:@"%@/%@/%@",[BTNetworkManager sharedMg].bathURL,typeStr,@(infoQuestionID)];
        }
        
        
        vc.url =url;
        
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }
    
    
    
}

- (void)noticePress {
    CWQ_MessageVC *messageVC = [CWQ_MessageVC new];
    [self.navigationController pushViewController:messageVC animated:YES];
}
- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}
- (void)configUI{


    
    UIButton *btn =[UIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage:[UIImage imageNamed:@"铃铛"] forState:UIControlStateNormal];
    
    [btn addTarget:self action:@selector(noticePress) forControlEvents:UIControlEventTouchUpInside];
    [btn showBadgeWithStyle:WBadgeStyleRedDot value:1 animationType:WBadgeAnimTypeBreathe];
    btn.badgeCenterOffset = CGPointMake(22, 8);
    btn.frame = CGRectMake(0, 0, 33, 33);
    self.notiBtn = btn;
    
    
    UIBarButtonItem *spaceFix = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    spaceFix.width = 14;
    UIBarButtonItem *rightItem =[[UIBarButtonItem alloc] initWithCustomView:btn];
    self.navigationItem.rightBarButtonItems = @[rightItem,spaceFix];

    XLPlainFlowLayout *layout =(XLPlainFlowLayout *)  self.collectionView.collectionViewLayout;
    
    self.navigationItem.titleView = self.searchBar;
    layout.sectionInset =UIEdgeInsetsMake(0, 0, 0, 0);
    layout.minimumInteritemSpacing = 2 ;
    layout.minimumLineSpacing = 2;
    CGFloat f = kScreenFactor;

    [self.collectionView registerNib:[UINib nibWithNibName:@"BTSchoolHorCell" bundle:nil] forCellWithReuseIdentifier:@"BTSchoolHorCell"];
      [self.collectionView registerNib:[UINib nibWithNibName:@"BTSchoolVerCell" bundle:nil] forCellWithReuseIdentifier:@"BTSchoolVerCell"];
    
   
    [self.collectionView registerNib:[UINib nibWithNibName:@"SchoolManagerSectionHeader" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"SchoolManagerSectionHeader"];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer"];
    
//    UIBarButtonItem *right2 =[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"搜索_icon.png"] style:0 target:self action:@selector(toSearch)];
//    
//    self.navigationItem.rightBarButtonItem = right2;
    
 
   
 
    [self getBanerData];
    weakSelf_define;
    [self.collectionView wsj_HeaderRefreshBlock:^{
        [weakSelf getManagerSchoolList];
    }];
    [weakSelf getManagerSchoolList];
    self.collectionView.contentInset = UIEdgeInsetsMake(f * banerHight , 0, 0, 0);
    self.banner.frame = CGRectMake(0, -f*banerHight, kScreenWidth, f * banerHight);
    [self.collectionView addSubview:self.banner];
    [self.collectionView bringSubviewToFront:self.collectionView.header];
    
   
    [self.collectionView.header setValue: [NSValue valueWithCGRect:CGRectMake(kScreenWidth /2, 200, kScreenWidth, self.collectionView.header.height)] forKey:@"frame"];
}


- (void)viewWillAppear:(BOOL)animated{
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    if (BT_USERID) {
         [self requestNoticeData];
    }
   
}

-(void)toSearch{
    CWQ_historySearchVC *vc =[CWQ_historySearchVC new];
    vc.searchType = CWQ_historySearchVCType_Course_Guanli;
    //wsjTest
   
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (BTSearchBar *)searchBar{
    if (!_searchBar) {
        _searchBar = [BTSearchBar searchBarWithDelegate:self];
        
    }
    return _searchBar;
}
#pragma -mark- --------------------获取通知消息----------------------
- (void)requestNoticeData {
    
    
    weakSelf_define;
    [[BTNetworkManager sharedMg] POST:BTNotifyReadUrl parameters:nil success:^(id responseObject) {
        if (responseObject_success) {
            
            if ([responseObject[@"data"] isKindOfClass:[NSDictionary class]]) {
                
                if([responseObject[@"data"][@"notReadNum"] integerValue]>0){
                      [weakSelf.notiBtn resumeBadge];
                } else {
                    
                    [weakSelf.notiBtn clearBadge];
                }
                
                
            }else{
                [weakSelf.notiBtn clearBadge];
            }
            
        }
    } failure:^(NSString *err) {
        
    }];
    
}
#pragma -mark 请求baner数据

- (void)getBanerData{
    weakSelf_define;
    [[BTNetworkManager sharedMg] POST:kGetBanner parameters:@{@"bannerType":@(2)} success:^(NSDictionary *responseObject) {
        if (responseObject[@"data"]) {
            NSArray<NSDictionary *> *arr = responseObject[@"data"] ;
            if ([arr isKindOfClass:[NSArray class]])  {
                weakSelf.bannerArr = [BTBannerModel mj_objectArrayWithKeyValuesArray:arr];
                
            }
            NSMutableArray *bannerImageArr =[NSMutableArray array];
            [weakSelf.bannerArr enumerateObjectsUsingBlock:^(BTBannerModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if (obj.bannerImage) {
                    [bannerImageArr addObject:[NSURL URLWithString:obj.bannerImage]];
                }
                
            }];
            [weakSelf.banner reloadData];
        }
        if (responseObject_Err) {
            alertMessage(responseObject[@"err"]);
        }
        
    } failure:^(NSString *err) {
        alertMessage(err);
    }];
    
}

#pragma mark -请求管理学院的数据
- (void)getManagerSchoolList{
    
    self.collectionView.loading =YES;
    weakSelf_define;
    [[BTNetworkManager sharedMg] POST:kManagerSchoolItemList parameters:nil success:^(NSDictionary * responseObject) {
        weakSelf.collectionView.loading =NO;
        if (responseObject_success) {
            [weakSelf.dataArray removeAllObjects];
            weakSelf.dataArray = [BTManagerItemModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
            [weakSelf.collectionView reloadData];
        }
        
        [weakSelf.collectionView.header endRefreshing];
    } failure:^(NSString *err) {
        weakSelf.collectionView.loading =NO;
        [weakSelf.collectionView.header endRefreshing];
    }];
    
    
}


- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return self.dataArray.count;
}


-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    BTManagerItemModel *model = self.dataArray[section];
    return model.courseflagList.count;
    
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
   
     BTManagerItemModel *model = self.dataArray[indexPath.section];
    NSInteger count = model.courseflagList.count;
    BTManagerItemModel *subModel =model.courseflagList[indexPath.row];
    if (count<=2) {
        BTSchoolHorCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"BTSchoolHorCell" forIndexPath:indexPath];
      
     
       [cell setImageUrl:subModel.iconUrl];
       [cell setTitleL:subModel.flagName];
        
        //    cell.titleL.text = str;
        return cell;
        
    }else{
        BTSchoolVerCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"BTSchoolVerCell" forIndexPath:indexPath];
        [cell setImageUrl:subModel.iconUrl];
        [cell setTitleL:subModel.flagName];
        //    cell.titleL.text = str;
        return cell;
    
    }
  
    
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
//    SchoolManagerSectionHeader
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        SchoolManagerSectionHeader *header = (SchoolManagerSectionHeader *)[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"SchoolManagerSectionHeader" forIndexPath:indexPath];
       BTManagerItemModel *model = self.dataArray[indexPath.section];
        header.titleL.text = model.flagName;
       
        return header;
    }else{
        UICollectionReusableView *footer =[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer" forIndexPath:indexPath];
        footer.backgroundColor = [UIColor clearColor];
        
        return footer;
        
    }
    return nil;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    BTManagerItemModel *model = self.dataArray[indexPath.section];
    NSInteger count = model.courseflagList.count;
    if (count <=2) {
        CGFloat f = kScreenFactor;
        return CGSizeMake((kScreenWidth -2)/2, f * 64);
    }else{
        CGFloat f = kScreenFactor;
        return CGSizeMake((kScreenWidth -2 * 2)/3, f * 70);
    }
   

}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
  
    CGFloat f =  kScreenFactor;
    return CGSizeMake(kScreenWidth, 30 * f);
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    if (section == 3) {
        return CGSizeMake(kScreenWidth, .1);
    }
    return CGSizeMake(kScreenWidth, 1);
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    BTManagerItemModel *model = self.dataArray[indexPath.section];
    BTManagerItemModel *subModel = model.courseflagList[indexPath.row];
    BTSchoolCourseList *vc = [BTSchoolCourseList new];
    vc.flagId = [subModel.id integerValue];
    vc.title = subModel.flagName;
    [self.navigationController pushViewController:vc animated:YES];
  
   
    
}

@end
